const Router = require('koa-router');
const { successMessage, errorMessage } = require("../../utils/send");
const { getQueryHomeData, createDataToHomeTable, updateDataToHomeTable, deleteDataFromHomeTable } = require('../../utils/sql');
const homeRouter = new Router();

//统一设置前缀
homeRouter.prefix('/home');

//查询首页列表web(显示);
homeRouter.get('/list', async (ctx, next) => {
    let {id,title,url} = ctx.query;
    let data = await getQueryHomeData(id,title,url);
    ctx.body = new successMessage({
        result: data
    }, 'success');
});

//收藏数据到首页列表
homeRouter.post('/create_data/home_list', async (ctx, next) => {
    let { title, des, url } = ctx.request.body;
    if (!title) {
        ctx.body = new errorMessage(null, '标题不能为空！');
        return false;
    };
    if (!url) {
        ctx.body = new errorMessage(null, '链接不能为空！');
        return false;
    };
    let isHave = await getQueryHomeData(title, "", "");
    if (isHave.length > 0) {
        ctx.body = new errorMessage(null, 'title名称已存在！');
        return false;
    }
    isHave = await getQueryHomeData('', "", url);
    if (isHave.length > 0) {
        ctx.body = new errorMessage(null, '当前url已存在！');
        return false;
    }
    let data = {
        title: title,
        des: des,
        url: url
    }
    let result = await createDataToHomeTable(data);
    if (result) {
        ctx.body = new successMessage(null, '收藏成功！')
    }

});

//首页数据编辑
homeRouter.post('/update/home_list', async (ctx, next) => {
    let { id, title, url, des } = ctx.request.body;
    if (!id) {
        ctx.body = new errorMessage(null, 'id不能为空！');
        return false;
    };
    let data = {
        id: id,
        title: title,
        des: des,
        url: url
    };
    let result = await updateDataToHomeTable(data);
    if (result) {
        ctx.body = new successMessage(null, '数据更新成功！')
    };
});

//首页数据删除
homeRouter.delete('/delete/home_list', async (ctx, next) => {
    let { id } = ctx.query;
    if (!id) {
        ctx.body = new errorMessage(null, 'id不能为空');
    };
    let result = await deleteDataFromHomeTable(id);
    if (result) {
        ctx.body = new successMessage(null, '删除成功');
    };
});


module.exports = {
    homeRouter
}